package com.freeze.demo.blockchain;

import java.util.Collections;
import java.util.List;

import com.alibaba.fastjson.JSON;

/**
 * <p>
 * Title: BlockChain
 * </p>
 * <p>
 * Description:
 * </p>
 * 
 * @author he_jiebing@jiuyv.com
 * @date 2021年4月9日 上午11:29:36
 */

public class BlockChain {

	private List<Block> chain;
	
	private List<Transaction> currentTransactions;

	public BlockChain() {
	}
	public BlockChain(List<Block> chain, List<Transaction> currentTransactions) {
		super();
		this.chain = chain;
		this.currentTransactions = currentTransactions;
	}
	

	public List<Block> getChain() {
		return chain;
	}

	public void setChain(List<Block> chain) {
		this.chain = chain;
	}

	public List<Transaction> getCurrentTransactions() {
		return currentTransactions;
	}

	public void setCurrentTransactions(List<Transaction> currentTransactions) {
		this.currentTransactions = currentTransactions;
	}

	/**
	 * 生成新的区块
	 * 
	 * @param self
	 * @param proof
	 * @param previousHash
	 * @return
	 */
	public Block newBlock(BlockChain self, long proof, String previousHash) {
		Block block = new Block();
		block.setIndex(self.getChain().size() + 1);
		block.setTimestamp(System.currentTimeMillis());
		block.setTransactions(self.getCurrentTransactions());
		block.setProof(proof);
		block.setPreviousHash(previousHash);
		// 重置当前交易记录
		self.setCurrentTransactions(Collections.EMPTY_LIST);
		self.getChain().add(block);
		return block;
	}

	/**
	 * 最后一个区块
	 * 
	 * @param self
	 */
	public Block lastBlock(BlockChain self) {
		// TODO 这一块没整明白，取得是后一个区块还是？
		return self.getChain().get(self.getChain().size() - 1);
	}
	/**
	 * hash
	 * @param block
	 * @return
	 */
	public String hash(Block block) {
		String calculatedhash = StringUtil.applySha256(JSON.toJSONString(block));
		return calculatedhash;

	}
	/**
	 * 生成新的交易
	 * @param self
	 * @param sender
	 * @param recipient
	 * @param amount
	 */
	public void newTransaction(BlockChain self, String sender, String recipient, long amount){
		Transaction transaction = new Transaction();
		transaction.setSender(sender);
		transaction.setRecipient(recipient);
		transaction.setAmount(amount);
		self.getCurrentTransactions().add(transaction);
		// TODO return self.last_block['index'] + 1
		//self.lastBlock(self)+1;
		
	}
	
	public long proofOfWork(BlockChain self,long lastProof){
		long proof = 0;
		while(!self.validProof(lastProof, proof)){
			proof += 1;
		}
		return proof;
		
	}
	/**
	 * TODO 
	 * @param lastProof
	 * @param proof
	 * @return
	 */
	public boolean validProof(long lastProof,long proof){
		// TODO pow 证明
		return false;
	}

}
